/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text, Table, TableRow, TableBody, Cell, useTheme, Button, TextArea,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, useInputControlSure,} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {tableSetInp} from "../../../common/tool";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";
import queryString from "query-string";
import {EditStorageContext} from "../../StorageContext";
import {useUppyUploadM} from "../../hook/useUppyUploadM";
import {DirectLink, Link as RouterLink} from "../../../routing/Link";
import {useFoldForList, useFoldGenerate, useSplitSubCapacity} from "../../hook/useMainRepUrlOr";

export interface Props extends InternalItemProps {
    table: string;
    dtitle?: string;
    memrow?:number;
}

//需要管理对象页面，可多次上传的（不是一次性上传几个图），采用useUppyUploadM。
export const AttachedPage=
    React.forwardRef(({ children, show ,alone=true,redId,nestMd,refWidth,rep,table,label,dtitle,memrow=8}:Props,  ref
    ) => {
        const theme= useTheme();
        const qs= queryString.parse(window.location.search);
        const dxtix =Number(qs?.dxtix) || 0;
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const itemA = React.useMemo(() => {
            return [ table,  ];
        }, [ table]);
        const [getInpFilter]=useMeasureInpFilter(null,itemA,);
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const dxtSize= inp?.[table]?.length || 0;
        const row=undefined===inp?.[table]?.[dxtix]? dxtSize : dxtix;
        const onFinish = React.useCallback(async(forRow:number, upfile: any, del:boolean) => {
            if(inp){
                tableSetInp(table, row, inp, onSure, '_FILE_', (del? undefined : upfile), del);
                !modified && setModified(true);
            }
        }, [row, inp, modified,table,onSure,setModified]);
        const [uploadDom]=useUppyUploadM({repId:rep?.id, table:table,
            row: row,  inp, setInp, onFinish, liveDays:1});

        return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={`${label}${dxtix + 1}的管理`}>
                <Text variant="h5">
                    {label}，序号 {dxtix + 1}：
                </Text>
                {dtitle??'缺陷附图或说明'}：
                <TextArea  value={inp?.[table]?.[dxtix]?.til || ''}  rows={memrow}
                           onChange={e => tableSetInp(table, dxtix, inp, setInp, 'til', e.currentTarget.value || undefined) } />
                {children}
                <hr/>
                {label} 附页附图的上传：
                {uploadDom}
                {!(inp?.[table]?.[row]?._FILE_?.url) &&
                    <Text variant="h5">
                        没有上传的文件，想要：
                        <Button intent="danger"
                                onPress={async () => {
                                    tableSetInp(table, row, inp, onSure, '_FILE_', undefined, true);
                                }}
                        >执行管理对象的删除</Button>，然后自行离开本界面，返回。
                    </Text>
                }
            </InspectRecordLayout>
        );
});

interface AttachedPageVwProps {
    orc: any;
    rep: any;
    children?: React.ReactNode;
    table: string;
    //折叠标签的名称：
    title?: string;
    dtitle?: string;
    hash?: string;       //？编辑器路由 +hash?
    op?:boolean;
    tmcap?: string;
}
/**编辑器组件可自定义的： 【局限性】只能支持一个图片的。
 * @param dxtix : 同一个重复分项的序号；
 *【铺满 1页A4纸张竖版 的】 minHeight: `calc(100vh - 6.5rem)`
 * */
export const AttachedPageVw= ({ orc, rep, children,table,title='附页',hash,op,dtitle,tmcap}: AttachedPageVwProps
) => {
    const theme= useTheme();
    const sizeDg=orc?.[table]?.length || 0;
    const lsBlockMax=useSplitSubCapacity(sizeDg,8);
    const {sumArea, areaContent, btnBindUses}=useFoldForList(orc?.[table], lsBlockMax,false);
    const callback = (dlPage: any, arak:number, pid:number) => {
        const aIdx= arak * lsBlockMax + pid;      //在总体列表中的顺序号。
        return <div key={aIdx} css={{"@media not print": {marginTop: '1rem', marginBottom: '1rem'},}}>
            <div css={{"@media print": {height: '100vh', overflowY: 'hidden',}}}>
                <DirectLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/AttachedPage#AttachedPage`}>
                    <Text variant="h3" css={{textAlign: 'center', marginTop: '1rem', "@media print": {pageBreakBefore: 'always', marginTop: 'unset',},}}>
                     {title}
                    </Text>
                    <div css={{display: 'flex', justifyContent: 'space-between'}}>
                        <Text>序号：{aIdx + 1}</Text>
                        <Text>{op?'记录':'报告'}编号：{rep.isp.no}</Text>
                    </div>
                </DirectLink>
                <Table fixed={["62%", "%"]} css={{
                              borderCollapse: 'collapse', "@media print": {minHeight: `calc(100vh - 6.5rem)`}
                            }} tight miniw={800}>
                    <TableBody>
                        <DirectLink
                            href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/AttachedPage?dxtix=` + aIdx+'&original=1' + `#AttachedPage`}>
                            <TableRow>
                                <Cell colSpan={2} css={{
                                    "@media print": {
                                        height: '-webkit-fill-available',
                                        pageBreakInside: 'avoid'
                                    }, padding: 0,
                                }}>
                                    {dtitle ?? '缺陷附图或说明'}：<br/>
                                    <div css={{whiteSpace: 'pre-wrap'}}>
                                        {orc?.[table]?.[aIdx]?.til}
                                    </div>
                                    <div css={{
                                        display: 'flex', justifyContent: 'space-around', alignItems: 'center',
                                        "@media print": {
                                            marginTop: '1px', marginRight: '1px', marginBottom: '1px',
                                            minHeight: '65vh'
                                        },
                                    }}>
                                        {orc?.[table]?.[aIdx]?._FILE_?.url &&
                                            <img
                                                src={process.env.REACT_APP_OSS_ENDP + orc?.[table]?.[aIdx]?._FILE_?.url}
                                                alt={orc?.[table]?.[aIdx]?._FILE_?.url}
                                                css={{
                                                    maxHeight: '14cm',
                                                    maxWidth: '-webkit-fill-available',
                                                    [theme.mediaQueries.lg]: {maxHeight: '18cm', maxWidth: undefined},
                                                    "@media print": {maxHeight: '86vh', maxWidth: '100%'},
                                                }}
                                            />
                                        }
                                    </div>
                                </Cell>
                            </TableRow>
                        </DirectLink>
                    </TableBody>
                </Table>
                <TailMenRowIspCheck cap={tmcap} orc={orc} rep={rep} href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ProjectList#ProjectList`}/>
            </div>
        </div>
    }

    const [renderAll]=useFoldGenerate({sumArea,btnBindUses,areaContent, callback,mark:title+'折叠'});
    const dxtNext= (orc?.[table]?.length || 0);
    return <>
        {sizeDg <= 0 &&
            <RouterLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/AttachedPage#AttachedPage`}>
                <Text  variant="h4" css={{
                    textAlign: 'center', marginTop: '1rem', "@media print": {display: 'none',},
                }}>{title}-附图附件的上传</Text>
            </RouterLink>
        }
        <div id={hash??"AttachedPage"}/>
        {renderAll}
        <RouterLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/AttachedPage?dxtix=${dxtNext}#AttachedPage`}>
            <Text variant="h4" css={{
                textAlign: 'center', "@media print": {display: 'none',},
            }}>新增加 {title}</Text>
        </RouterLink>
    </>;
};
